#include <iostream>
#include <string>
#include <functional>
#include <unordered_map>
#include "include/muduo/net/TcpServer.h"
#include "include/muduo/net/EventLoop.h"
#include "include/muduo/net/TcpConnection.h"

class TranslateServer
{
public:
    TranslateServer(int port) : _server(&_loop, muduo::net::InetAddress("0.0.0.0", port), "translate_server", muduo::net::TcpServer::kReusePort)
    {
        _server.setConnectionCallback(std::bind(&TranslateServer::onConnection, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&TranslateServer::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }

    void start()
    {
        // 开启服务器的监听接口
        _server.start();
        // 开启服务器的事件监听循环
        _loop.loop();
    }

    ~TranslateServer() {}

private:
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        // 连接建立成功/断开连接时被调用的函数
        if (conn->connected())
        {
            std::cout << "连接建立成功" << std::endl;
        }
        else if (conn->disconnected())
        {
            std::cout << "断开连接" << std::endl;
        }
    }

    void translate(std::string& str)
    {
        static const std::unordered_map<std::string, std::string> dict = {
            {"hello", "你好"},
            {"你好", "hello"},
            {"苹果", "apple"},
            {"apple", "苹果"}
        };

        if(dict.find(str) != dict.end())
        {
            str = dict.at(str);
        }
        else
        {
            str = "我不知道！";
        }
    }

    void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buffer, muduo::Timestamp)
    {
        // 消息到来时被调用的函数
        // 1. 接受发来的消息
        std::string str = buffer->retrieveAllAsString();
        translate(str);
        conn->send(str);
    }

private:
    muduo::net::EventLoop _loop;
    muduo::net::TcpServer _server;
};

int main()
{
    TranslateServer ts(8080);
    ts.start();
    
    return 0;
}